from machine import Timer
from machine import Pin
import time
import gc


class BodySensor:
    def __init__(self, led=None):

        self._led = led
        if self._led is None:
            self._led = Pin(2, Pin.OUT, value=1)

        # GPIO15 (D8)
        self._sensor = Pin(15, Pin.IN)
        self._check_body_timer = Timer(0)

        self._last_time = 0
        self._interval = 30
        self._locked = 0

    def _check_body(self, timer):
        try:

            if self._locked == 0:
                value = self._sensor.value()
                if value == 1:
                    self._led.value(0)  # on
                    self._locked = 1

            if (time.time() - self._last_time) > self._interval:
                self._locked = 0
                self._led.value(1)  # off
                self._last_time = time.time()

        except OSError as e:
            print(e)
            time.sleep(1)
            self._check_message_timer.deinit()
            self.start()

        gc.collect()

    def start(self):

        self._check_body_timer.init(
            mode=Timer.PERIODIC,
            period=10,
            callback=self._check_body
        )

        gc.collect()
